<template>
  <view class="index-page" :class="{ 'dark-mode': isDarkMode }">
    <!-- 头部操作按钮 -->
    <view class="header-buttons">
      <view class="back-to-top-btn" @click="scrollToTop" :class="{ 'show': showBackToTop }">
        <text class="btn-icon">⬆️</text>
      </view>
      <view class="theme-toggle" @click="toggleTheme">
        <text class="theme-icon">{{ isDarkMode ? '☀️' : '🌙' }}</text>
      </view>
    </view>
    <u-sticky>
      <view
        class="header-section"
        :class="{ 'dark-mode': isDarkMode }"
      >
        <view
          class="date-selector"
          :class="{ 'dark-mode': isDarkMode }"
          @click.stop="show = true"
        >
          <view class="date-text">{{ rq_from }}</view>
          <text class="date-separator">~</text>
          <view class="date-text">{{ rq_to }}</view>
        </view>
        <view class="search-row">
          <view class="search-input-wrapper">
            <u-input
              v-model="data.searchvalue"
              type="text"
              border
              clearable
              :custom-style="isDarkMode ? darkInputStyle : lightInputStyle"
            />
          </view>
          <view class="button-group">
            <u-button
              size="medium"
              type="primary"
              @click.stop="search"
              :custom-style="isDarkMode ? darkButtonStyle : lightButtonStyle"
            >查询</u-button>
            <u-button
              size="medium"
              type="primary"
              @click.stop="showInput = true"
              :custom-style="isDarkMode ? darkButtonStyle : lightButtonStyle"
            >输入</u-button>
          </view>
        </view>
      </view>
    </u-sticky>

    <u-popup
      v-model="showInput"
      mode="top"
      :custom-style="isDarkMode ? darkPopupStyle : lightPopupStyle"
    >
      <view class="popup-content" :class="{ 'dark-mode': isDarkMode }">
        <u-input
          placeholder="请输入requestid"
          border="surround"
          v-model="requestid"
          :custom-style="isDarkMode ? darkInputStyle : lightInputStyle"
        ></u-input>
        <u-input
          style="margin-top: 1rem"
          placeholder="请输入checkid"
          border="surround"
          v-model="checkid"
          :custom-style="isDarkMode ? darkInputStyle : lightInputStyle"
        ></u-input>
        <u-button
          size="medium"
          type="primary"
          @click.stop="save"
          :custom-style="isDarkMode ? darkButtonStyle : lightButtonStyle"
        >确定</u-button>
      </view>
    </u-popup>
    <u-calendar
      v-model="show"
      mode="range"
      @change="change"
      :custom-style="isDarkMode ? darkCalendarStyle : lightCalendarStyle"
    ></u-calendar>
    <u-tabs
      :list="data.namelist"
      :is-scroll="false"
      v-model="data.currentIndex"
      @change="namechange"
      :custom-style="isDarkMode ? darkTabsStyle : lightTabsStyle"
    ></u-tabs>

    <!-- 决策面板 -->
    <view class="decision-panel" :class="{ 'dark-mode': isDarkMode }">
      <view class="panel-header" @click="toggleDecisionPanel">
        <text class="panel-title">📊 决策分析</text>
        <text class="panel-toggle">{{ showDecisionPanel ? '▼' : '▶' }}</text>
      </view>
      <view v-if="showDecisionPanel" class="panel-content">
        <!-- 时间范围选择 -->
        <view class="time-range-selector">
          <text class="selector-label">统计范围:</text>
          <view class="range-options">
            <text
              class="range-option"
              :class="{ 'active': analysisTimeRange === 24 }"
              @click="changeAnalysisTimeRange(24)"
            >24小时</text>
            <text
              class="range-option"
              :class="{ 'active': analysisTimeRange === 72 }"
              @click="changeAnalysisTimeRange(72)"
            >3天</text>
          </view>
        </view>
        <view class="analysis-section">
          <view class="section-title">🎯 大小球分析</view>
          <view class="analysis-item">
            <text class="label">小于2.5球最频繁:</text>
            <view class="value">
              <text
                v-for="(team, index) in decisionData.under25Teams"
                :key="index"
                class="team-link"
                @click="searchTeam(team)"
              >
                {{ team }}{{ index < decisionData.under25Teams.length - 1 ? ', ' : '' }}
              </text>
              <text v-if="decisionData.under25Teams.length === 0" class="no-data">暂无数据</text>
            </view>
          </view>
          <view class="analysis-item">
            <text class="label">大于2.5球最频繁:</text>
            <view class="value">
              <text
                v-for="(team, index) in decisionData.over25Teams"
                :key="index"
                class="team-link"
                @click="searchTeam(team)"
              >
                {{ team }}{{ index < decisionData.over25Teams.length - 1 ? ', ' : '' }}
              </text>
              <text v-if="decisionData.over25Teams.length === 0" class="no-data">暂无数据</text>
            </view>
          </view>
          <view class="analysis-item">
            <text class="label">小球率最高队伍:</text>
            <view class="value">
              <text
                v-for="(team, index) in decisionData.highestUnder25Teams"
                :key="index"
                class="team-link"
                @click="searchTeam(team)"
              >
                {{ team }}{{ index < decisionData.highestUnder25Teams.length - 1 ? ', ' : '' }}
              </text>
              <text v-if="decisionData.highestUnder25Teams.length === 0" class="no-data">暂无数据</text>
            </view>
          </view>
        </view>
        <view class="analysis-section">
          <view class="section-title">⚽ 上半场分析</view>
          <view class="analysis-item">
            <text class="label">上半场0球概率高:</text>
            <view class="value">
              <text
                v-for="(team, index) in decisionData.firstHalfNoGoalTeams"
                :key="index"
                class="team-link"
                @click="searchTeam(team)"
              >
                {{ team }}{{ index < decisionData.firstHalfNoGoalTeams.length - 1 ? ', ' : '' }}
              </text>
              <text v-if="decisionData.firstHalfNoGoalTeams.length === 0" class="no-data">暂无数据</text>
            </view>
          </view>
          <view class="analysis-item">
            <text class="label">上半场0球概率最小:</text>
            <view class="value">
              <text
                v-for="(team, index) in decisionData.firstHalfMostLikelyGoalTeams"
                :key="index"
                class="team-link"
                @click="searchTeam(team)"
              >
                {{ team }}{{ index < decisionData.firstHalfMostLikelyGoalTeams.length - 1 ? ', ' : '' }}
              </text>
              <text v-if="decisionData.firstHalfMostLikelyGoalTeams.length === 0" class="no-data">暂无数据</text>
            </view>
          </view>
          <view class="analysis-item">
            <text class="label">上半场0-0最多队伍:</text>
            <view class="value">
              <text
                v-for="(team, index) in decisionData.firstHalf00Teams"
                :key="index"
                class="team-link"
                @click="searchTeam(team)"
              >
                {{ team }}{{ index < decisionData.firstHalf00Teams.length - 1 ? ', ' : '' }}
              </text>
              <text v-if="decisionData.firstHalf00Teams.length === 0" class="no-data">暂无数据</text>
            </view>
          </view>
        </view>
        <view class="update-time">
          <text>更新时间: {{ decisionData.updateTime }}</text>
        </view>
      </view>
    </view>

    <!-- 球队对比分析面板 -->
    <view class="team-comparison-panel" :class="{ 'dark-mode': isDarkMode }">
      <view class="panel-header" @click="toggleComparisonPanel">
        <text class="panel-title">⚽ 球队对比分析</text>
        <text class="panel-toggle">{{ showComparisonPanel ? '▼' : '▶' }}</text>
      </view>
      <view v-if="showComparisonPanel" class="panel-content">
        <!-- 球队选择 -->
        <view class="team-selector">
          <view class="team-select-row">
            <text class="select-label">主队:</text>
            <view class="team-picker" @click="openTeamSelector('home')">
              <view class="picker-text">{{ selectedHomeTeam || '请选择主队' }}</view>
              <text class="picker-arrow">▼</text>
            </view>
          </view>
          <view class="team-select-row">
            <text class="select-label">客队:</text>
            <view class="team-picker" @click="openTeamSelector('away')">
              <view class="picker-text">{{ selectedAwayTeam || '请选择客队' }}</view>
              <text class="picker-arrow">▼</text>
            </view>
          </view>
          <button
            class="analyze-btn"
            :class="{ 'dark-mode': isDarkMode }"
            @click="analyzeTeamComparison"
            :disabled="!selectedHomeTeam || !selectedAwayTeam"
          >
            开始分析
          </button>
        </view>

        <!-- 分析结果 -->
        <view v-if="comparisonResult.analyzed" class="comparison-result">
          <view class="result-section">
            <view class="section-title">🎯 上半场大小球建议</view>
            <view class="recommendation">
              <view class="rec-item">
                <text class="rec-label">建议:</text>
                <text class="rec-value" :class="comparisonResult.firstHalf.recommendation === '大球' ? 'big-ball' : 'small-ball'">
                  {{ comparisonResult.firstHalf.recommendation }}
                </text>
              </view>
              <view class="rec-item">
                <text class="rec-label">概率:</text>
                <text class="rec-value">{{ comparisonResult.firstHalf.probability }}%</text>
              </view>
              <view class="rec-item">
                <text class="rec-label">依据:</text>
                <text class="rec-reason">{{ comparisonResult.firstHalf.reason }}</text>
              </view>
            </view>
          </view>

          <view class="result-section">
            <view class="section-title">⚽ 全场大小球建议</view>
            <view class="recommendation">
              <view class="rec-item">
                <text class="rec-label">建议:</text>
                <text class="rec-value" :class="comparisonResult.fullTime.recommendation === '大球' ? 'big-ball' : 'small-ball'">
                  {{ comparisonResult.fullTime.recommendation }}
                </text>
              </view>
              <view class="rec-item">
                <text class="rec-label">概率:</text>
                <text class="rec-value">{{ comparisonResult.fullTime.probability }}%</text>
              </view>
              <view class="rec-item">
                <text class="rec-label">依据:</text>
                <text class="rec-reason">{{ comparisonResult.fullTime.reason }}</text>
              </view>
            </view>
          </view>

          <view class="team-stats">
            <view class="stats-title">📊 双方数据对比</view>
            <view class="stats-comparison">
              <view class="team-stat">
                <text class="team-name">{{ selectedHomeTeam }}</text>
                <text class="stat-item">上半场进球率: {{ comparisonResult.homeTeam.firstHalfGoalRate }}%</text>
                <text class="stat-item">全场大球率: {{ comparisonResult.homeTeam.fullTimeBigRate }}%</text>
                <text class="stat-item">参与比赛: {{ comparisonResult.homeTeam.totalMatches }}场</text>
              </view>
              <text class="vs-divider">VS</text>
              <view class="team-stat">
                <text class="team-name">{{ selectedAwayTeam }}</text>
                <text class="stat-item">上半场进球率: {{ comparisonResult.awayTeam.firstHalfGoalRate }}%</text>
                <text class="stat-item">全场大球率: {{ comparisonResult.awayTeam.fullTimeBigRate }}%</text>
                <text class="stat-item">参与比赛: {{ comparisonResult.awayTeam.totalMatches }}场</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 独立的对比分析结果列表 -->
    <view v-if="comparisonMatches.length > 0" class="comparison-results-section" :class="{ 'dark-mode': isDarkMode }">
      <view class="section-header">
        <text class="section-title">📋 相关比赛记录 ({{ comparisonMatches.length }}场)</text>
        <button class="clear-btn" @click="clearComparisonResults">清空</button>
      </view>
      <view class="comparison-matches-list">
        <view
          class="comparison-match-item"
          :class="{
            'mini': cacul(item.all) < 3,
            'dark-mode': isDarkMode,
            'direct-match': isDirectMatch(item)
          }"
          v-for="(item, index) in comparisonMatches"
          :key="index"
        >
          <view class="team-info">
            <view class="team-vs">
              <view class="teamname home" :class="{ 'highlight': item.homeName === selectedHomeTeam || item.homeName === selectedAwayTeam }">{{ item.homeName }}</view>
              <text class="vs-text">VS</text>
              <view class="teamname away" :class="{ 'highlight': item.awayName === selectedHomeTeam || item.awayName === selectedAwayTeam }">{{ item.awayName }}</view>
            </view>
          </view>
          <view class="score-section">
            <view class="score-row">
              <text class="score-item">{{ item.b }}</text>
              <text class="score-item total">{{ item.all }}</text>
            </view>
          </view>
          <view class="time-info">
            {{ totime(item.matchTime) }}
          </view>
        </view>
      </view>
    </view>

    <view class="match-list">
      <view
        class="match-item"
        :class="{
          mini: cacul(item.all) < 3,
          'dark-mode': isDarkMode
        }"
        v-for="(item, index) in data.list"
        :key="index"
      >
        <view class="team-info">
          <view class="team-vs">
            <view class="teamname home" :title="item.homeName">{{ truncateTeamName(item.homeName) }}</view>
            <text class="vs-text">VS</text>
            <view class="teamname away" :title="item.awayName">{{ truncateTeamName(item.awayName) }}</view>
          </view>
        </view>
        <view class="score-section">
          <view class="score-row">
            <text class="score-item half">{{ item.b }}</text>
            <text class="score-item second-half">{{  item.a }}</text>
            <text class="score-item total">{{ item.all }}</text>
          </view>
          <view class="score-labels">
            <text class="score-label">上半</text>
            <text class="score-label">下半</text>
            <text class="score-label">全场</text>
          </view>
        </view>
        <view class="time-info">
          {{ totime(item.matchTime) }}
        </view>
      </view>
    </view>

    <u-no-network></u-no-network>

    <!-- 球队选择弹出框 -->
    <u-popup
      v-model="showTeamSelector"
      mode="center"
      :border-radius="20"
      :closeable="true"
      width="95%"
      height="80%"
      :safe-area-inset-bottom="true"
      :z-index="999"
    >
      <view class="team-selector-popup" :class="{ 'dark-mode': isDarkMode }">
        <view class="popup-header">
          <text class="popup-title">选择{{ currentSelectType === 'home' ? '主队' : '客队' }}</text>
          <view class="close-btn" @click="closeTeamSelector">✕</view>
        </view>
        <scroll-view
          class="teams-grid-container"
          scroll-y="true"
          :enhanced="true"
          :show-scrollbar="true"
          :enable-back-to-top="false"
        >
          <view class="teams-grid">
            <view
              v-for="(team, index) in availableTeams"
              :key="index"
              class="team-grid-item"
              :class="{
                'selected': (currentSelectType === 'home' && team === selectedHomeTeam) ||
                           (currentSelectType === 'away' && team === selectedAwayTeam),
                'dark-mode': isDarkMode
              }"
              @click="selectTeam(team)"
            >
              <text class="team-name-text">{{ team }}</text>
            </view>
          </view>
        </scroll-view>
      </view>
    </u-popup>

    <u-toast ref="uToast" />
  </view>
</template>

<script setup lang="ts">
import titlebar from '@/components/common/title-bar.vue'
import { onShow, onLoad } from '@dcloudio/uni-app'
import { storeToRefs } from 'pinia'
import { useStore } from '@/store'
import dayjs from 'dayjs'
import { find, sum, uniqBy,concat } from 'lodash-es'

// 获取自定义的store
const store = useStore()

// 取需要的 state
const { user } = storeToRefs(store)
import { userApi, carApi } from '@/api'
import { reactive, ref, getCurrentInstance, watch, onMounted } from 'vue'
const proxy = getCurrentInstance()?.proxy ?? null

// 夜间模式相关
const isDarkMode = ref(false)

// 决策面板相关
const showDecisionPanel = ref(false)
const analysisTimeRange = ref(24) // 默认24小时
const decisionData = reactive({
  under25Teams: [],
  over25Teams: [],
  highestUnder25Teams: [], // 新增：小球率最高的队伍
  firstHalfNoGoalTeams: [],
  firstHalfGoalTeams: [],
  firstHalfMostLikelyGoalTeams: [], // 新增：上半场0球概率最小的队伍
  firstHalf00Teams: [], // 新增：上半场0-0最多的队伍
  updateTime: ''
})

// 球队对比面板相关
const showComparisonPanel = ref(false)
const selectedHomeTeam = ref('')
const selectedAwayTeam = ref('')
const homeTeamIndex = ref(0)
const awayTeamIndex = ref(0)
const availableTeams = ref([])
const comparisonMatches = ref([]) // 独立的对比分析结果列表

// 球队选择弹出框相关
const showTeamSelector = ref(false)
const currentSelectType = ref('') // 'home' 或 'away'
let isLeagueChange = false // 标记是否是联赛切换触发的搜索
let isTeamSearch = false // 标记是否是点击队伍名称触发的搜索
const comparisonResult = reactive({
  analyzed: false,
  firstHalf: {
    recommendation: '',
    probability: 0,
    reason: ''
  },
  fullTime: {
    recommendation: '',
    probability: 0,
    reason: ''
  },
  homeTeam: {
    firstHalfGoalRate: 0,
    fullTimeBigRate: 0,
    totalMatches: 0
  },
  awayTeam: {
    firstHalfGoalRate: 0,
    fullTimeBigRate: 0,
    totalMatches: 0
  }
})

// 主题切换函数
const toggleTheme = () => {
  isDarkMode.value = !isDarkMode.value
  // 保存到本地存储
  uni.setStorageSync('darkMode', isDarkMode.value)
}

// 返回顶部相关
const showBackToTop = ref(false)

// 返回顶部功能
const scrollToTop = () => {
  uni.pageScrollTo({
    scrollTop: 0,
    duration: 300
  })
}

// 裁剪队伍名字
const truncateTeamName = (name) => {
  if (!name) return ''
  return name.length > 6 ? name.substring(0, 6) + '...' : name
}

// 解析比分字符串，返回总进球数
const parseScore = (scoreStr) => {
  if (!scoreStr) return 0
  if (typeof scoreStr === 'number') return scoreStr

  // 如果是字符串格式如"2-1"，计算总进球数
  const parts = scoreStr.toString().split('-')
  if (parts.length === 2) {
    const home = parseInt(parts[0]) || 0
    const away = parseInt(parts[1]) || 0
    return home + away
  }

  // 如果不是标准格式，尝试直接转换为数字
  return parseInt(scoreStr) || 0
}


// 从本地存储加载主题设置
const loadThemeFromStorage = () => {
  try {
    const savedTheme = uni.getStorageSync('darkMode')
    if (savedTheme !== '') {
      isDarkMode.value = savedTheme
    }
  } catch (e) {
    console.log('加载主题设置失败:', e)
  }
}

// 切换决策面板显示状态
const toggleDecisionPanel = () => {
  showDecisionPanel.value = !showDecisionPanel.value
  if (showDecisionPanel.value) {
    analyzeMatchData()
  }
}

// 切换分析时间范围
const changeAnalysisTimeRange = (hours: number) => {
  analysisTimeRange.value = hours
  if (showDecisionPanel.value) {
    analyzeMatchData()
  }
}

// 获取置信度等级（去掉星号）
const getConfidenceLevel = (rate, total) => {
  return '' // 不再显示星号
}

// 获取置信度分数（用于排序）
const getConfidenceScore = (rate, total) => {
  // 综合考虑概率和样本数量
  const sampleWeight = Math.min(total / 10, 1) // 10场比赛为满权重
  const rateWeight = Math.abs(rate - 0.5) * 2 // 距离50%越远权重越高
  return rateWeight * sampleWeight
}

// 分析比赛数据
const analyzeMatchData = () => {
  console.log('开始分析比赛数据，总数据量:', data.list?.length)
  if (!data.list || data.list.length === 0) {
    console.log('没有比赛数据')
    return
  }

  // 根据时间范围过滤比赛数据
  const now = dayjs()
  const timeThreshold = now.subtract(analysisTimeRange.value, 'hour')

  const filteredMatches = data.list.filter(match => {
    const matchTime = dayjs(Number(match.matchTime))
    // 检查比赛时间是否在指定范围内（过去N小时到现在）
    return matchTime.isAfter(timeThreshold) && matchTime.isBefore(now)
  })

  // 如果时间过滤后没有数据，则使用所有数据进行分析
  const matchesToAnalyze = filteredMatches.length > 0 ? filteredMatches : data.list
  console.log(`时间过滤后数据量: ${filteredMatches.length}, 实际分析数据量: ${matchesToAnalyze.length}`)

  // 统计各队伍的大小球情况
  const teamStats = {}

  matchesToAnalyze.forEach(match => {
    const homeTeam = match.homeName
    const awayTeam = match.awayName

    // 检查数据字段，可能字段名不同
    const totalGoals = (match.allHome || match.all || 0) + (match.allAway || 0)
    const firstHalfGoals = (match.bHome || match.b || 0) + (match.bAway || 0)

    // 如果字段名不对，尝试其他可能的字段名
    const actualTotalGoals = totalGoals || match.all || 0
    const actualFirstHalfGoals = firstHalfGoals || match.b || 0

    console.log(`比赛: ${homeTeam} vs ${awayTeam}, 全场: ${actualTotalGoals}, 上半场: ${actualFirstHalfGoals}`)

    // 初始化队伍统计（添加上半场0-0统计）
    if (!teamStats[homeTeam]) {
      teamStats[homeTeam] = {
        under25: 0,
        over25: 0,
        firstHalfNoGoal: 0,
        firstHalfGoal: 0,
        firstHalf00: 0, // 新增：上半场0-0次数
        total: 0
      }
    }
    if (!teamStats[awayTeam]) {
      teamStats[awayTeam] = {
        under25: 0,
        over25: 0,
        firstHalfNoGoal: 0,
        firstHalfGoal: 0,
        firstHalf00: 0, // 新增：上半场0-0次数
        total: 0
      }
    }

    // 统计大小球
    if (actualTotalGoals < 2.5) {
      teamStats[homeTeam].under25++
      teamStats[awayTeam].under25++
    } else {
      teamStats[homeTeam].over25++
      teamStats[awayTeam].over25++
    }

    // 统计上半场进球情况（分别统计每支球队的上半场进球）
    const homeFirstHalf = match.bHome || 0
    const awayFirstHalf = match.bAway || 0

    // 主队上半场进球统计
    if (homeFirstHalf > 0) {
      teamStats[homeTeam].firstHalfGoal++
    } else {
      teamStats[homeTeam].firstHalfNoGoal++
    }

    // 客队上半场进球统计
    if (awayFirstHalf > 0) {
      teamStats[awayTeam].firstHalfGoal++
    } else {
      teamStats[awayTeam].firstHalfNoGoal++
    }

    // 统计上半场0-0的情况
    if (homeFirstHalf === 0 && awayFirstHalf === 0) {
      teamStats[homeTeam].firstHalf00++
      teamStats[awayTeam].firstHalf00++
    }

    teamStats[homeTeam].total++
    teamStats[awayTeam].total++
  })

  // 找出最频繁的队伍和小球率最高的队伍
  const under25Teams = []
  const over25Teams = []
  const highestUnder25Teams = []
  const firstHalfNoGoalTeams = []
  const firstHalfGoalTeams = []
  const firstHalfMostLikelyGoalTeams = []
  const firstHalf00Teams = [] // 新增：上半场0-0最多的球队

  // 用于找出小球率最高的队伍
  const teamRates = []
  // 用于找出上半场0球概率最小的队伍
  const firstHalfNoGoalRates = []
  // 用于找出上半场0-0最多的队伍
  const firstHalf00Rates = []

  Object.entries(teamStats).forEach(([team, stats]) => {
    if (stats.total >= 3) { // 提高到至少3场比赛才有统计意义
      const under25Rate = stats.under25 / stats.total
      const over25Rate = stats.over25 / stats.total
      const noGoalRate = stats.firstHalfNoGoal / stats.total
      const goalRate = stats.firstHalfGoal / stats.total
      const firstHalf00Rate = stats.firstHalf00 / stats.total // 上半场0-0概率

      // 优化的动态阈值系统
      const confidenceLevel = stats.total >= 8 ? 0.65 : stats.total >= 5 ? 0.7 : stats.total >= 3 ? 0.75 : 0.8

      // 小球队伍：动态阈值 + 置信度标识
      if (under25Rate >= confidenceLevel) {
        const confidence = getConfidenceLevel(under25Rate, stats.total)
        under25Teams.push(`${team}(${(under25Rate*100).toFixed(0)}%/${stats.total}场${confidence})`)
      }

      // 大球队伍：动态阈值 + 置信度标识
      if (over25Rate >= confidenceLevel) {
        const confidence = getConfidenceLevel(over25Rate, stats.total)
        over25Teams.push(`${team}(${(over25Rate*100).toFixed(0)}%/${stats.total}场${confidence})`)
      }

      // 上半场无球：动态阈值，样本越少要求越高
      const noGoalThreshold = stats.total >= 8 ? 0.6 : stats.total >= 5 ? 0.65 : stats.total >= 3 ? 0.7 : 0.75
      if (noGoalRate >= noGoalThreshold) {
        const confidence = getConfidenceLevel(noGoalRate, stats.total)
        firstHalfNoGoalTeams.push(`${team}(${(noGoalRate*100).toFixed(0)}%/${stats.total}场${confidence})`)
      }

      // 上半场有球：动态阈值，样本越少要求越高
      const goalThreshold = stats.total >= 8 ? 0.6 : stats.total >= 5 ? 0.65 : stats.total >= 3 ? 0.7 : 0.75
      if (goalRate >= goalThreshold) {
        const confidence = getConfidenceLevel(goalRate, stats.total)
        firstHalfGoalTeams.push(`${team}(${(goalRate*100).toFixed(0)}%/${stats.total}场${confidence})`)
      }

      // 上半场0-0：统计次数而非概率，至少2次且概率超过30%
      if (stats.firstHalf00 >= 2 && firstHalf00Rate >= 0.3) {
        firstHalf00Teams.push(`${team}(${stats.firstHalf00}次/${stats.total}场,${(firstHalf00Rate*100).toFixed(0)}%)`)
      }

      // 收集所有队伍的小球率用于排序（添加置信度分数）
      teamRates.push({
        team: team,
        under25Rate: under25Rate,
        total: stats.total,
        confidence: getConfidenceScore(under25Rate, stats.total)
      })

      // 收集所有队伍的上半场0球概率用于排序（添加置信度分数）
      firstHalfNoGoalRates.push({
        team: team,
        noGoalRate: noGoalRate,
        total: stats.total,
        confidence: getConfidenceScore(1 - noGoalRate, stats.total) // 进球概率的置信度
      })

      // 收集所有队伍的上半场0-0数据用于排序
      firstHalf00Rates.push({
        team: team,
        firstHalf00Count: stats.firstHalf00,
        firstHalf00Rate: firstHalf00Rate,
        total: stats.total
      })
    }
  })

  // 找出小球率最高的队伍（按置信度分数排序，综合考虑概率和样本数）
  teamRates.sort((a, b) => b.confidence - a.confidence)
  teamRates.slice(0, 5).forEach(item => {
    if (item.under25Rate >= 0.65 && item.total >= 2) { // 降低阈值，但用置信度筛选
      const confidence = getConfidenceLevel(item.under25Rate, item.total)
      highestUnder25Teams.push(`${item.team}(${(item.under25Rate*100).toFixed(0)}%/${item.total}场${confidence})`)
    }
  })

  // 找出上半场0球概率最小的队伍（按进球置信度排序）
  firstHalfNoGoalRates.sort((a, b) => b.confidence - a.confidence)
  firstHalfNoGoalRates.slice(0, 5).forEach(item => {
    if (item.noGoalRate <= 0.4 && item.total >= 2) { // 0球概率40%以下且至少2场比赛才显示
      const goalProbability = ((1 - item.noGoalRate) * 100).toFixed(0) // 修复计算公式
      const confidence = getConfidenceLevel(1 - item.noGoalRate, item.total)
      firstHalfMostLikelyGoalTeams.push(`${item.team}(进球率${goalProbability}%/${item.total}场${confidence})`)
    }
  })

  // 找出上半场0-0最多的队伍（按次数排序）
  firstHalf00Rates.sort((a, b) => b.firstHalf00Count - a.firstHalf00Count)
  firstHalf00Rates.slice(0, 5).forEach(item => {
    if (item.firstHalf00Count >= 2) { // 至少2次0-0才显示
      // 不显示置信度标识，直接显示次数和概率
      // firstHalf00Teams 已经在上面的循环中填充了，这里不需要重复添加
    }
  })

  // 添加调试信息
  console.log('上半场统计调试信息:')
  console.log('firstHalfNoGoalTeams:', firstHalfNoGoalTeams)
  console.log('firstHalfGoalTeams:', firstHalfGoalTeams)
  console.log('分析的比赛数量:', matchesToAnalyze.length)

  // 输出一些队伍的详细统计
  Object.entries(teamStats).slice(0, 3).forEach(([team, stats]) => {
    const noGoalRate = stats.firstHalfNoGoal / stats.total
    const goalRate = stats.firstHalfGoal / stats.total
    console.log(`${team}: 总场次${stats.total}, 上半场无球${stats.firstHalfNoGoal}场(${(noGoalRate*100).toFixed(1)}%), 上半场有球${stats.firstHalfGoal}场(${(goalRate*100).toFixed(1)}%)`)
  })

  // 更新决策数据
  decisionData.under25Teams = under25Teams.slice(0, 5) // 最多显示5个
  decisionData.over25Teams = over25Teams.slice(0, 5)
  decisionData.highestUnder25Teams = highestUnder25Teams
  decisionData.firstHalfNoGoalTeams = firstHalfNoGoalTeams.slice(0, 5)
  decisionData.firstHalfGoalTeams = firstHalfGoalTeams.slice(0, 5)
  decisionData.firstHalfMostLikelyGoalTeams = firstHalfMostLikelyGoalTeams
  decisionData.firstHalf00Teams = firstHalf00Teams.slice(0, 5) // 新增：上半场0-0最多的队伍
  decisionData.updateTime = `${dayjs().format('HH:mm:ss')} (${analysisTimeRange.value}h内, ${matchesToAnalyze.length}场比赛)`
}

// 搜索指定球队
const searchTeam = (teamWithRate: string) => {
  // 提取球队名称（去掉所有括号及其内容）
  const teamName = teamWithRate.split('(')[0].trim()

  // 保存当前的决策分析结果
  const savedDecisionData = {
    under25Teams: [...decisionData.under25Teams],
    over25Teams: [...decisionData.over25Teams],
    highestUnder25Teams: [...decisionData.highestUnder25Teams],
    firstHalfNoGoalTeams: [...decisionData.firstHalfNoGoalTeams],
    firstHalfGoalTeams: [...decisionData.firstHalfGoalTeams],
    firstHalfMostLikelyGoalTeams: [...decisionData.firstHalfMostLikelyGoalTeams],
    updateTime: decisionData.updateTime
  }

  // 设置搜索值
  data.searchvalue = teamName

  // 标记这是队伍搜索，防止重新分析决策数据
  isTeamSearch = true

  // 执行搜索
  search().then(() => {
    // 搜索完成后恢复决策分析结果
    Object.assign(decisionData, savedDecisionData)
    // 重置标志
    isTeamSearch = false
  })

  // 显示提示
  uni.showToast({
    title: `正在搜索 ${teamName}`,
    icon: 'none',
    duration: 1500
  })

  // 可选：折叠决策面板以显示更多搜索结果
  // showDecisionPanel.value = false
}

// 球队对比面板相关函数
const toggleComparisonPanel = () => {
  showComparisonPanel.value = !showComparisonPanel.value
  if (showComparisonPanel.value) {
    updateAvailableTeams()
  }
}

// 更新可选球队列表
const updateAvailableTeams = () => {
  if (!data.list || data.list.length === 0) {
    availableTeams.value = []
    return
  }

  const teams = new Set()
  data.list.forEach(match => {
    teams.add(match.homeName)
    teams.add(match.awayName)
  })

  availableTeams.value = Array.from(teams).sort()
}

// 打开球队选择器
const openTeamSelector = (type) => {
  currentSelectType.value = type
  showTeamSelector.value = true
}

// 关闭球队选择器
const closeTeamSelector = () => {
  showTeamSelector.value = false
  currentSelectType.value = ''
}

// 选择球队
const selectTeam = (team) => {
  if (currentSelectType.value === 'home') {
    selectedHomeTeam.value = team
    homeTeamIndex.value = availableTeams.value.indexOf(team)
  } else if (currentSelectType.value === 'away') {
    selectedAwayTeam.value = team
    awayTeamIndex.value = availableTeams.value.indexOf(team)
  }

  comparisonResult.analyzed = false
  closeTeamSelector()
}

// 主队选择变化（保留兼容性）
const onHomeTeamChange = (e) => {
  homeTeamIndex.value = e.detail.value
  selectedHomeTeam.value = availableTeams.value[e.detail.value]
  comparisonResult.analyzed = false
}

// 客队选择变化（保留兼容性）
const onAwayTeamChange = (e) => {
  awayTeamIndex.value = e.detail.value
  selectedAwayTeam.value = availableTeams.value[e.detail.value]
  comparisonResult.analyzed = false
}

// 分析球队对比
const analyzeTeamComparison = () => {
  if (!selectedHomeTeam.value || !selectedAwayTeam.value) {
    uni.showToast({
      title: '请选择双方球队',
      icon: 'none'
    })
    return
  }

  if (selectedHomeTeam.value === selectedAwayTeam.value) {
    uni.showToast({
      title: '请选择不同的球队',
      icon: 'none'
    })
    return
  }

  // 统计两支球队的历史数据
  const homeTeamStats = analyzeTeamStats(selectedHomeTeam.value)
  const awayTeamStats = analyzeTeamStats(selectedAwayTeam.value)

  // 生成建议
  generateRecommendations(homeTeamStats, awayTeamStats)

  comparisonResult.analyzed = true

  // 自动搜索两队对战历史
  searchTeamHistory(selectedHomeTeam.value, selectedAwayTeam.value)

  uni.showToast({
    title: '分析完成，正在搜索对战历史',
    icon: 'success',
    duration: 2000
  })
}

// 分析单个球队的统计数据（优化版）
const analyzeTeamStats = (teamName) => {
  const teamMatches = data.list.filter(match =>
    match.homeName === teamName || match.awayName === teamName
  )

  if (teamMatches.length === 0) {
    return {
      totalMatches: 0,
      firstHalfGoalRate: 0,
      fullTimeBigRate: 0,
      firstHalfGoals: 0,
      fullTimeGoals: 0,
      recentForm: 0,
      homeAwayBalance: 0
    }
  }

  // 不在这里设置比赛列表，在生成建议时统一处理
  // comparisonMatches.value = [...teamMatches]

  let firstHalfWithGoals = 0
  let fullTimeBigBalls = 0
  let totalFirstHalfGoals = 0
  let totalFullTimeGoals = 0
  let recentMatches = 0
  let recentBigBalls = 0
  let homeMatches = 0
  let awayMatches = 0
  let homeBigBalls = 0
  let awayBigBalls = 0

  // 按时间排序，分析最近的比赛趋势
  const sortedMatches = teamMatches.sort((a, b) => b.matchTime - a.matchTime)

  sortedMatches.forEach((match, index) => {
    const firstHalfGoals = match.bHome + match.bAway
    const fullTimeGoals = match.allHome + match.allAway
    const isHome = match.homeName === teamName

    totalFirstHalfGoals += firstHalfGoals
    totalFullTimeGoals += fullTimeGoals

    if (firstHalfGoals > 0) firstHalfWithGoals++
    if (fullTimeGoals > 2.5) fullTimeBigBalls++

    // 主客场统计
    if (isHome) {
      homeMatches++
      if (fullTimeGoals > 2.5) homeBigBalls++
    } else {
      awayMatches++
      if (fullTimeGoals > 2.5) awayBigBalls++
    }

    // 最近5场比赛的趋势
    if (index < 5) {
      recentMatches++
      if (fullTimeGoals > 2.5) recentBigBalls++
    }
  })

  return {
    totalMatches: teamMatches.length,
    firstHalfGoalRate: Math.round((firstHalfWithGoals / teamMatches.length) * 100),
    fullTimeBigRate: Math.round((fullTimeBigBalls / teamMatches.length) * 100),
    avgFirstHalfGoals: (totalFirstHalfGoals / teamMatches.length).toFixed(1),
    avgFullTimeGoals: (totalFullTimeGoals / teamMatches.length).toFixed(1),
    recentForm: recentMatches > 0 ? Math.round((recentBigBalls / recentMatches) * 100) : 0,
    homeAwayBalance: {
      home: homeMatches > 0 ? Math.round((homeBigBalls / homeMatches) * 100) : 0,
      away: awayMatches > 0 ? Math.round((awayBigBalls / awayMatches) * 100) : 0
    }
  }
}

// 生成建议（优化版）
const generateRecommendations = (homeStats, awayStats) => {
  // 获取两支球队的所有比赛
  const homeTeamMatches = data.list.filter(match =>
    match.homeName === selectedHomeTeam.value || match.awayName === selectedHomeTeam.value
  )

  const awayTeamMatches = data.list.filter(match =>
    match.homeName === selectedAwayTeam.value || match.awayName === selectedAwayTeam.value
  )

  // 合并两队比赛，保留所有比赛（包括重复的）
  const allMatches = [...homeTeamMatches, ...awayTeamMatches]

  // 使用 Map 来去重，但保留所有相关比赛
  const matchMap = new Map()
  allMatches.forEach(match => {
    const key = `${match.homeName}-${match.awayName}-${match.matchTime}`
    if (!matchMap.has(key)) {
      matchMap.set(key, match)
    }
  })

  const uniqueMatches = Array.from(matchMap.values())

  // 按是否为直接对战排序，直接对战的排在前面
  const sortedMatches = uniqueMatches.sort((a, b) => {
    const aIsDirect = isDirectMatch(a)
    const bIsDirect = isDirectMatch(b)

    if (aIsDirect && !bIsDirect) return -1
    if (!aIsDirect && bIsDirect) return 1

    // 如果都是直接对战或都不是，按时间倒序排列
    return b.matchTime - a.matchTime
  })

  // 设置对比分析结果列表
  comparisonMatches.value = sortedMatches

  // 更新球队统计显示
  comparisonResult.homeTeam = {
    firstHalfGoalRate: homeStats.firstHalfGoalRate,
    fullTimeBigRate: homeStats.fullTimeBigRate,
    totalMatches: homeStats.totalMatches
  }

  comparisonResult.awayTeam = {
    firstHalfGoalRate: awayStats.firstHalfGoalRate,
    fullTimeBigRate: awayStats.fullTimeBigRate,
    totalMatches: awayStats.totalMatches
  }

  // 计算样本可靠性权重
  const totalSamples = homeStats.totalMatches + awayStats.totalMatches
  const reliabilityWeight = Math.min(totalSamples / 20, 1) // 20场比赛为满权重

  // 上半场建议（优化算法）
  const homeFirstHalfWeight = homeStats.totalMatches / totalSamples
  const awayFirstHalfWeight = awayStats.totalMatches / totalSamples
  const weightedFirstHalfRate = (homeStats.firstHalfGoalRate * homeFirstHalfWeight +
                                awayStats.firstHalfGoalRate * awayFirstHalfWeight)

  // 考虑最近表现的影响
  const recentFormFactor = (homeStats.recentForm + awayStats.recentForm) / 2
  const adjustedFirstHalfRate = weightedFirstHalfRate * 0.7 + recentFormFactor * 0.3

  if (adjustedFirstHalfRate >= 75 && reliabilityWeight >= 0.6) {
    comparisonResult.firstHalf = {
      recommendation: '大球',
      probability: Math.round(adjustedFirstHalfRate * reliabilityWeight),
      reason: `双方上半场进球率高(${homeStats.firstHalfGoalRate}% vs ${awayStats.firstHalfGoalRate}%)，样本可靠度${Math.round(reliabilityWeight*100)}%`
    }
  } else if (adjustedFirstHalfRate <= 25 && reliabilityWeight >= 0.6) {
    comparisonResult.firstHalf = {
      recommendation: '小球',
      probability: Math.round((100 - adjustedFirstHalfRate) * reliabilityWeight),
      reason: `双方上半场进球率低(${homeStats.firstHalfGoalRate}% vs ${awayStats.firstHalfGoalRate}%)，样本可靠度${Math.round(reliabilityWeight*100)}%`
    }
  } else {
    comparisonResult.firstHalf = {
      recommendation: adjustedFirstHalfRate >= 50 ? '大球' : '小球',
      probability: Math.round(Math.abs(adjustedFirstHalfRate - 50) + 50),
      reason: `数据倾向性不明显(${homeStats.firstHalfGoalRate}% vs ${awayStats.firstHalfGoalRate}%)，建议谨慎`
    }
  }

  // 全场建议（优化算法）
  const weightedFullTimeRate = (homeStats.fullTimeBigRate * homeFirstHalfWeight +
                               awayStats.fullTimeBigRate * awayFirstHalfWeight)

  // 主客场因素调整
  const homeAdvantage = homeStats.homeAwayBalance?.home || homeStats.fullTimeBigRate
  const awayDisadvantage = awayStats.homeAwayBalance?.away || awayStats.fullTimeBigRate
  const homeAwayAdjustment = (homeAdvantage - awayDisadvantage) * 0.1

  const adjustedFullTimeRate = weightedFullTimeRate + homeAwayAdjustment

  if (adjustedFullTimeRate >= 75 && reliabilityWeight >= 0.6) {
    comparisonResult.fullTime = {
      recommendation: '大球',
      probability: Math.round(adjustedFullTimeRate * reliabilityWeight),
      reason: `双方大球率高(${homeStats.fullTimeBigRate}% vs ${awayStats.fullTimeBigRate}%)，主客场调整${homeAwayAdjustment > 0 ? '+' : ''}${homeAwayAdjustment.toFixed(1)}%`
    }
  } else if (adjustedFullTimeRate <= 25 && reliabilityWeight >= 0.6) {
    comparisonResult.fullTime = {
      recommendation: '小球',
      probability: Math.round((100 - adjustedFullTimeRate) * reliabilityWeight),
      reason: `双方大球率低(${homeStats.fullTimeBigRate}% vs ${awayStats.fullTimeBigRate}%)，主客场调整${homeAwayAdjustment > 0 ? '+' : ''}${homeAwayAdjustment.toFixed(1)}%`
    }
  } else {
    comparisonResult.fullTime = {
      recommendation: adjustedFullTimeRate >= 50 ? '大球' : '小球',
      probability: Math.round(Math.abs(adjustedFullTimeRate - 50) + 50),
      reason: `综合分析倾向性不强(${homeStats.fullTimeBigRate}% vs ${awayStats.fullTimeBigRate}%)，样本${totalSamples}场`
    }
  }
}

// 搜索两队对战历史（不影响主搜索框）
const searchTeamHistory = (homeTeam, awayTeam) => {
  // 保存当前搜索值
  const originalSearchValue = data.searchvalue

  // 直接从当前数据中筛选相关比赛，不进行新的搜索
  const directMatches = data.list.filter(match =>
    (match.homeName === homeTeam && match.awayName === awayTeam) ||
    (match.homeName === awayTeam && match.awayName === homeTeam)
  )

  // 如果有直接对战记录
  if (directMatches.length > 0) {
    comparisonMatches.value = directMatches
    uni.showToast({
      title: `找到 ${directMatches.length} 场直接对战记录`,
      icon: 'success',
      duration: 2000
    })
    return
  }

  // 如果没有直接对战记录，搜索包含任一球队的比赛
  const relatedMatches = data.list.filter(match =>
    match.homeName === homeTeam || match.awayName === homeTeam ||
    match.homeName === awayTeam || match.awayName === awayTeam
  )

  if (relatedMatches.length > 0) {
    comparisonMatches.value = relatedMatches
    uni.showToast({
      title: `未找到直接对战，显示 ${relatedMatches.length} 场相关比赛`,
      icon: 'none',
      duration: 2000
    })
  } else {
    // 如果当前数据中没有相关比赛，则进行后台搜索但不改变主搜索框
    searchTeamHistoryInBackground(homeTeam, awayTeam, originalSearchValue)
  }
}

// 后台搜索球队历史（不影响主搜索框显示）
const searchTeamHistoryInBackground = async (homeTeam, awayTeam, originalSearchValue) => {
  try {
    // 临时保存当前列表
    const originalList = [...data.list]

    // 后台搜索主队比赛
    data.searchvalue = homeTeam
    await search()

    // 从搜索结果中筛选相关比赛
    const homeTeamMatches = data.list.filter(match =>
      match.homeName === homeTeam || match.awayName === homeTeam
    )

    // 搜索客队比赛
    data.searchvalue = awayTeam
    await search()

    const awayTeamMatches = data.list.filter(match =>
      match.homeName === awayTeam || match.awayName === awayTeam
    )

    // 合并并去重
    const allMatches = [...homeTeamMatches, ...awayTeamMatches]
    const uniqueMatches = allMatches.filter((match, index, self) =>
      index === self.findIndex(m => m.id === match.id)
    )

    // 设置对比结果
    comparisonMatches.value = uniqueMatches

    // 恢复原始搜索状态
    data.searchvalue = originalSearchValue
    data.list = originalList

    uni.showToast({
      title: `找到 ${uniqueMatches.length} 场相关比赛记录`,
      icon: 'success',
      duration: 2000
    })

  } catch (error) {
    console.error('搜索球队历史失败:', error)
    uni.showToast({
      title: '搜索失败，请重试',
      icon: 'none',
      duration: 2000
    })
  }
}

// 判断是否为直接对战
const isDirectMatch = (match) => {
  return (match.homeName === selectedHomeTeam.value && match.awayName === selectedAwayTeam.value) ||
         (match.homeName === selectedAwayTeam.value && match.awayName === selectedHomeTeam.value)
}

// 清空对比分析结果
const clearComparisonResults = () => {
  comparisonMatches.value = []
  comparisonResult.analyzed = false
}

// 夜间模式样式配置
const darkInputStyle = {
  backgroundColor: '#3d3d3d',
  borderColor: '#555',
  color: '#ffffff'
}

const lightInputStyle = {
  backgroundColor: '#ffffff',
  borderColor: '#ddd',
  color: '#333333'
}

const darkButtonStyle = {
  backgroundColor: '#0a84ff',
  color: '#ffffff'
}

const lightButtonStyle = {
  backgroundColor: '#007aff',
  color: '#ffffff'
}

const darkPopupStyle = {
  backgroundColor: '#2d2d2d'
}

const lightPopupStyle = {
  backgroundColor: '#ffffff'
}

const darkCalendarStyle = {
  backgroundColor: '#2d2d2d',
  color: '#ffffff'
}

const lightCalendarStyle = {
  backgroundColor: '#ffffff',
  color: '#333333'
}

const darkTabsStyle = {
  backgroundColor: '#2d2d2d',
  color: '#ffffff'
}

const lightTabsStyle = {
  backgroundColor: '#ffffff',
  color: '#333333'
}
const data = reactive({
  namelist: [

    {
      name: '中',
      code: '677711777777496777'
    },
    {
      name: '英',
      code: '888811777777496888'
    },
    {
      name: '法',
      code: '688811888887496888'
    },
	{
	  name: '欧',
	  code: '847835101681946629'
	},
    {
      name: '西',
      code: '599911889987496999'
    },
    {
      name: '意',
      code: '343311880987496449'
    },
	{
	  name: '德',
	  code: '699911889987496999'
	},
	{
	  name: '美',
	  code: '258835101681949925'
	},{
		
		name:'国',
		code:'289882682225555528'
	},{
    name:'南',
    code:'278992683332727227'
  }
	
  ],
  list: [],
  searchvalue: '',
  currentname: '352541568130764801',
  currentIndex: 0
})

const lists = reactive([{ item: '22' }, { item: '22' }])
const isLoad = ref(false)
const selectall = ref(false)
const selectMutifi = ref(false)
const show = ref(false)
const showInput = ref(false)
const rq_from = ref(``)
const rq_to = ref(``)
const params = reactive({
  year: true,
  month: true,
  day: true,
  hour: false,
  minute: false,
  second: false
})

const cacul = (str: string) => {
  let fen = str.split(':')
  return Number(Number(fen[0]) + Number(fen[1]))
}

const requestid = ref('')
const checkid = ref('')
onLoad((query: any) => {
  // 加载主题设置
  loadThemeFromStorage()

  // 设置默认日期
  rq_from.value = dayjs().add(-2, 'day').format('YYYYMMDD')
  rq_to.value = dayjs().add(1, 'day').format('YYYYMMDD')
  console.log(rq_to.value)
  search()
})

const search = async () => {
  // 保存当前的球队对比分析结果
  const savedComparisonResult = comparisonResult.analyzed ? {
    analyzed: comparisonResult.analyzed,
    firstHalf: { ...comparisonResult.firstHalf },
    fullTime: { ...comparisonResult.fullTime },
    homeTeam: { ...comparisonResult.homeTeam },
    awayTeam: { ...comparisonResult.awayTeam }
  } : null

  data.list = []
  await getlist(1)
  // await getlist(2);
  // await getlist(3);

  // 搜索完成后，如果决策面板是展开的且不是队伍搜索，则重新分析数据
  if (showDecisionPanel.value && !isTeamSearch) {
    analyzeMatchData()
  }

  // 如果球队对比面板是展开的，则更新可选球队列表
  if (showComparisonPanel.value) {
    updateAvailableTeams()

    // 恢复之前保存的分析结果（如果存在）
    if (savedComparisonResult) {
      Object.assign(comparisonResult, savedComparisonResult)
    }
  }

  return Promise.resolve()
}
const save = () => {
store.setUserInput(checkid.value, requestid.value)
  showInput.value = false
}

const getlist = (page: number) => {
  return new Promise((resolve, reject) => {
    uni.showLoading()

    const postdata = {
      tournamentId: data.currentname,
      runningBar: '0',
      isPlayBack: 0,
      orderBy: 0,
      sportType: '1',
      startTime: Number(
        dayjs(dayjs(rq_from.value).format('YYYYMMDD 00:00:00')).unix() + '000'
      ),
      endTime: Number(
        dayjs(dayjs(rq_to.value).format('YYYYMMDD 23:59:59')).unix() + '000'
      ),
      langType: 'zh',
      page: { current: page, size: 200 },
      isVirtualSport: '',
      matchNameStr: data.searchvalue,
      champion: 0,
      isESport: ''
    }
    carApi
      .getlist(postdata)
      .then((res) => {
        if (res.data == null || res.data == undefined) {
          uni.showToast({
            title: res.msg
          })
          setTimeout(() => {
            reject()
          }, 1000)
        } else {
          const list = res.data.records
          list.forEach((x) => {
            const s = JSON.parse(x.scoreResult)
            const a = s[3].split('|')[1]
            const b = s[2].split('|')[1]
            const all = s[0].split('|')[1]
            
            // 拆分比分
            const [aHome, aAway] = a.split(':').map(Number)
            const [bHome, bAway] = b.split(':').map(Number)
            const [allHome, allAway] = all.split(':').map(Number)

            x.a = a
            x.b = b
            x.all = all
            x.aHome = aHome
            x.aAway = aAway
            x.bHome = bHome
            x.bAway = bAway
            x.allHome = allHome
            x.allAway = allAway
            x.time = dayjs(x.matchTime, 'x').format('MM/DD HH:mm')
          })
          data.list = uniqBy(concat(data.list, list), 'matchId')
          



          resolve(list)
        }
      })
      .finally(() => {
        reject()
        uni.hideLoading()
      })
  })
}
const change = (params) => {
  rq_from.value = params.startDate
  rq_to.value = params.endDate
}

const namechange = (index) => {
  data.currentname = data.namelist[index].code

  // 切换联赛时清空搜索框
  data.searchvalue = ''

  // 如果球队对比面板是展开的，重置对比状态
  if (showComparisonPanel.value) {
    selectedHomeTeam.value = ''
    selectedAwayTeam.value = ''
    homeTeamIndex.value = 0
    awayTeamIndex.value = 0
    comparisonResult.analyzed = false
  }

  // 标记这是联赛切换触发的搜索，需要重置分析状态
  isLeagueChange = true
  search().then(() => {
    isLeagueChange = false
  })
}
const goto = (item) => {
  if (!selectMutifi.value) {
    carApi.getsingle(item.id).then((res) => {
      uni.navigateTo({
        url: `/pages/driverInformation/vehicleRegistrationInput?id=${item.id}`
      })
    })
  } else {
    item.checked = !item.checked
  }
}

const totime = (item) => {
  var date = new Date(Number(item)) // 创建 Date 对象
  var year = date.getFullYear() // 获取年份
  var month = date.getMonth() + 1 // 获取月份，需要加 1
  var day = date.getDate() // 获取日期
  var hour = date.getHours() // 获取小时
  var minute = date.getMinutes() // 获取分钟
  return dayjs(date).format('MM/DD HH:mm')
  //  var result = month + "/" + day + " " + hour + ":" + minute; // 拼接结果

  //return result;
}

// 页面滚动监听函数（供页面调用）
const onPageScroll = (e: any) => {
  showBackToTop.value = e.scrollTop > 300
}

// 生命周期函数
onMounted(() => {
  // 从本地存储恢复夜间模式设置
  const savedDarkMode = uni.getStorageSync('darkMode')
  if (savedDarkMode !== undefined) {
    isDarkMode.value = savedDarkMode
  }

  // 简化版本：显示返回顶部按钮（当有数据时显示）
  setTimeout(() => {
    showBackToTop.value = true
  }, 2000)
})

onShow(() => {
  // 页面显示时的逻辑
})

// 导出页面滚动函数供页面使用
defineExpose({
  onPageScroll
})

</script>

<style lang="scss" scoped>
/* 基础页面样式 */
.index-page {
  font-style: normal;
  padding-top: 60rpx;
  padding-left: 10rpx;
  padding-right: 10rpx;
  min-height: 100vh;
  background-color: #f5f5f5;
  transition: all 0.3s ease;

  &.dark-mode {
    background-color: #1a1a1a;
    color: #ffffff;
  }
}

/* 头部操作按钮 */
.header-buttons {
  position: fixed;
  top: 100rpx;
  right: 30rpx;
  z-index: 1000;
  display: flex;
  flex-direction: column;
  gap: 15rpx;
}

.back-to-top-btn {
  width: 70rpx;
  height: 70rpx;
  border-radius: 50%;
  background: rgba(0, 122, 255, 0.8);
  backdrop-filter: blur(10rpx);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  opacity: 0;
  transform: translateY(20rpx);
  cursor: pointer;

  &.show {
    opacity: 1;
    transform: translateY(0);
  }

  &:hover {
    background: rgba(0, 122, 255, 1);
    transform: scale(1.1);
  }

  .btn-icon {
    font-size: 28rpx;
    color: white;
  }
}

.theme-toggle {
  width: 70rpx;
  height: 70rpx;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10rpx);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover {
    background-color: rgba(0, 0, 0, 0.2);
    transform: scale(1.1);
  }
}

.theme-icon {
  font-size: 32rpx;
}

/* 头部区域 */
.header-section {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;
  padding: 15rpx;
  background-color: white;
  width: 100%;
  border-bottom: 1rpx solid #e0e0e0;
  transition: all 0.3s ease;

  &.dark-mode {
    background-color: #2d2d2d;
    border-bottom-color: #404040;
  }
}

/* 日期选择器 */
.date-selector {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10rpx 0;
  cursor: pointer;
  width: 100%;

  &.dark-mode {
    color: #ffffff;
  }
}

.date-text {
  font-size: 28rpx;
  font-weight: 500;
}

.date-separator {
  margin: 0 20rpx;
  font-size: 24rpx;
}

/* 搜索行 */
.search-row {
  display: flex;
  align-items: center;
  width: 100%;
  gap: 20rpx;
}

.search-input-wrapper {
  flex: 1;
}

.button-group {
  display: flex;
  gap: 10rpx;
}

/* 弹窗内容 */
.popup-content {
  padding: 2rem;
  transition: all 0.3s ease;

  &.dark-mode {
    background-color: #2d2d2d;
    color: #ffffff;
  }
}

/* 比赛列表 */
.match-list {
  padding: 5rpx;
}

/* 比赛项目 */
.match-item {
  display: flex;
  align-items: center;
  padding: 8rpx 10rpx;
  margin-bottom: 6rpx;
  background-color: white;
  border-radius: 6rpx;
  box-shadow: 0 1rpx 3rpx rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  min-height: 60rpx;

  &.mini {
    background-color: #a7f740;
  }

  &.dark-mode {
    background-color: #2d2d2d;
    box-shadow: 0 1rpx 3rpx rgba(255, 255, 255, 0.1);
    color: #ffffff;

    &.mini {
      background-color: #4a5d23;
    }
  }
}

.team-info {
  flex: 2;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.team-vs {
  display: flex;
  align-items: center;
  gap: 6rpx;
  flex-wrap: nowrap;
}

.teamname {
  flex: 1;
  text-align: center;
  font-size: 20rpx;
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  min-width: 0;

  &.home {
    text-align: right;
  }

  &.away {
    text-align: left;
  }
}

.vs-text {
  font-size: 16rpx;
  color: #999;
  flex-shrink: 0;
  font-weight: bold;
}

/* 比分区域 */
.score-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  min-width: 140rpx;
  flex-shrink: 0;
}

.score-row {
  display: flex;
  align-items: center;
  gap: 6rpx;
  margin-bottom: 4rpx;
}

.score-labels {
  display: flex;
  gap: 6rpx;
}

.score-label {
  font-size: 16rpx;
  color: #999;
  min-width: 32rpx;
  text-align: center;

  .match-item.dark-mode & {
    color: #ccc;
  }
}

.score-item {
  font-size: 18rpx;
  padding: 4rpx 8rpx;
  border-radius: 4rpx;
  min-width: 32rpx;
  text-align: center;
  color: #8b8a8a;
  font-weight: 600;
  border: 1rpx solid transparent;

  &.half {
    background-color: #d1ecf1;
    color: #0c5460;
    border-color: #bee5eb;
  }

  &.second-half {
    background-color: #ffeaa7;
    color: #94928c;
    border-color: #e4e4e1;
  }

  &.total {
    background-color: #007aff;
    color: white;
    font-weight: 700;
    border-color: #0056b3;
  }
}

/* 夜间模式下的比分样式 */
.match-item.dark-mode .score-item {
  color: #ffffff;

  &.half {
    background-color: #1a365d;
    color: #90cdf4;
    border-color: #2d5a87;
  }

  &.second-half {
    background-color: #d4d2d1;
    color: #424241;
    border-color: #a0621e;
  }

  &.total {
    background-color: #0a84ff;
    color: white;
    border-color: #0066cc;
  }
}

.time-info {
  font-size: 18rpx;
  color: #666;
  text-align: center;
  min-width: 90rpx;
  flex-shrink: 0;
}

/* 夜间模式下的时间信息 */
.match-item.dark-mode .time-info {
  color: #ccc;
}

/* 夜间模式下的 VS 文字 */
.match-item.dark-mode .vs-text {
  color: #999;
}

/* 决策面板样式 */
.decision-panel {
  margin: 10rpx;
  background-color: white;
  border-radius: 8rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;

  &.dark-mode {
    background-color: #2d2d2d;
    box-shadow: 0 2rpx 8rpx rgba(255, 255, 255, 0.1);
  }
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
  cursor: pointer;

  .decision-panel.dark-mode & {
    border-bottom-color: #404040;
  }
}

.panel-title {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;

  .decision-panel.dark-mode & {
    color: #ffffff;
  }
  .team-comparison-panel.dark-mode & {
    color: #ffffff;
  }
}

.panel-toggle {
  font-size: 24rpx;
  color: #666;

  .decision-panel.dark-mode & {
    color: #ccc;
  }
}

.panel-content {
  padding: 20rpx;
}

/* 时间范围选择器样式 */
.time-range-selector {
  display: flex;
  align-items: center;
  margin-bottom: 25rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;

  .decision-panel.dark-mode & {
    border-bottom-color: #404040;
  }
}

.selector-label {
  font-size: 24rpx;
  color: #666;
  margin-right: 20rpx;
  flex-shrink: 0;

  .decision-panel.dark-mode & {
    color: #ccc;
  }
}

.range-options {
  display: flex;
  gap: 15rpx;
}

.range-option {
  font-size: 24rpx;
  padding: 8rpx 20rpx;
  border-radius: 20rpx;
  background-color: #f5f5f5;
  color: #666;
  cursor: pointer;
  transition: all 0.3s ease;

  &.active {
    background-color: #007aff;
    color: white;
  }

  &:hover:not(.active) {
    background-color: #e8e8e8;
  }

  .decision-panel.dark-mode & {
    background-color: #4a4a4a;
    color: #ccc;

    &.active {
      background-color: #0a84ff;
      color: white;
    }

    &:hover:not(.active) {
      background-color: #555;
    }
  }
}

.analysis-section {
  margin-bottom: 25rpx;
  padding: 15rpx;
  background-color: #fafafa;
  border-radius: 8rpx;
  border-left: 4rpx solid #007aff;

  &:last-child {
    margin-bottom: 0;
  }

  .decision-panel.dark-mode & {
    background-color: #3a3a3a;
    border-left-color: #0a84ff;
  }
}

.section-title {
  font-size: 28rpx;
  font-weight: 700;
  color: #007aff;
  margin-bottom: 15rpx;
  display: flex;
  align-items: center;

  .decision-panel.dark-mode & {
    color: #66b3ff;
  }
}

.analysis-item {
  display: flex;
  margin-bottom: 15rpx;
  align-items: flex-start;
  padding: 10rpx;
  background-color: white;
  border-radius: 6rpx;
  box-shadow: 0 1rpx 3rpx rgba(0, 0, 0, 0.1);

  &:last-child {
    margin-bottom: 0;
  }

  .decision-panel.dark-mode & {
    background-color: #2d2d2d;
    box-shadow: 0 1rpx 3rpx rgba(255, 255, 255, 0.1);
  }
}

.label {
  font-size: 22rpx;
  color: #555;
  min-width: 180rpx;
  flex-shrink: 0;
  font-weight: 600;

  .decision-panel.dark-mode & {
    color: #e0e0e0;
  }
}

.value {
  font-size: 22rpx;
  color: #333;
  flex: 1;
  line-height: 1.4;
  font-weight: 500;

  .decision-panel.dark-mode & {
    color: #f5f5f5;
  }
}

.team-link {
  color: #007aff;
  cursor: pointer;
  text-decoration: underline;
  transition: all 0.3s ease;
  font-weight: 600;

  &:hover {
    color: #0056cc;
    opacity: 0.8;
  }

  &:active {
    opacity: 0.6;
  }

  .decision-panel.dark-mode & {
    color: #66b3ff;

    &:hover {
      color: #99ccff;
    }
  }
}

.no-data {
  color: #999;
  font-style: italic;

  .decision-panel.dark-mode & {
    color: #666;
  }
}

.update-time {
  margin-top: 20rpx;
  padding-top: 15rpx;
  border-top: 1rpx solid #f0f0f0;
  text-align: center;

  .decision-panel.dark-mode & {
    border-top-color: #404040;
  }

  text {
    font-size: 22rpx;
    color: #999;

    .decision-panel.dark-mode & {
      color: #666;
    }
  }
}

/* 其他样式保持兼容 */
.h2 {
  color: green;
  font-size: 50rpx;
}

navigator {
  color: #1e80ff;
}

.container {
  padding: 20rpx 60rpx;
}

.userinfo {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.userinfo-avatar {
  width: 128rpx;
  height: 128rpx;
  margin: 20rpx;
  border-radius: 50%;
}

.lists {
  margin: 10px 0;
}

.second-title {
  font-size: 22rpx;
}

.info {
  font-size: 20rpx;
}

.tag {
  margin-left: 5rpx;
  margin-right: 5rpx;
}

.item {
  display: flex;
  padding: 20rpx;
}

/* 球队对比面板样式 */
.team-comparison-panel {
  margin: 10rpx;
  background-color: white;
  border-radius: 8rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;

  &.dark-mode {
    background-color: #2d2d2d;
    box-shadow: 0 2rpx 8rpx rgba(255, 255, 255, 0.1);
  }
}

/* 球队选择器 */
.team-selector {
  margin-bottom: 30rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;

  .team-comparison-panel.dark-mode & {
    border-bottom-color: #404040;
  }
}

.team-select-row {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.select-label {
  font-size: 26rpx;
  color: #333;
  width: 100rpx;
  flex-shrink: 0;
  font-weight: 600;

  .team-comparison-panel.dark-mode & {
    color: #f5f5f5;
  }
}

.team-picker {
  flex: 1;
  margin-left: 20rpx;
  cursor: pointer;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  transition: all 0.3s ease;

  &:hover {
    background-color: #e8e8e8;
  }

  .team-comparison-panel.dark-mode & {
    background-color: #4a4a4a;
    border: 1rpx solid #666;

    &:hover {
      background-color: #555;
    }
  }
}

.picker-text {
  font-size: 26rpx;
  color: #333;
  font-weight: 500;
  flex: 1;

  .team-comparison-panel.dark-mode & {
    color: #f0f0f0;
  }
}

.picker-arrow {
  font-size: 20rpx;
  color: #999;
  margin-left: 10rpx;
  transition: transform 0.3s ease;

  .team-comparison-panel.dark-mode & {
    color: #ccc;
  }
}

.analyze-btn {
  width: 200rpx;
  padding: 5rpx 10rpx;
  background-color: #007aff;
  color: white;
  border: none;
  border-radius: 6rpx;
  font-size: 26rpx;
  font-weight: 500;
  margin: 15rpx auto 0;
  display: block;

  &:disabled {
    background-color: #ccc;
    color: #999;
  }

  &.dark-mode {
    background-color: #0a84ff;
    color: #f5f5f5;

    &:disabled {
      background-color: #555;
      color: #888;
    }
  }
}

/* 分析结果样式 */
.comparison-result {
  margin-top: 30rpx;
}

.result-section {
  margin-bottom: 30rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.recommendation {
  background-color: #f8f9fa;
  padding: 20rpx;
  border-radius: 8rpx;
  margin-top: 15rpx;

  .team-comparison-panel.dark-mode & {
    background-color: #3a3a3a;
  }
}

.rec-item {
  display: flex;
  margin-bottom: 10rpx;
  align-items: flex-start;

  &:last-child {
    margin-bottom: 0;
  }
}

.rec-label {
  font-size: 24rpx;
  color: #666;
  min-width: 100rpx;
  flex-shrink: 0;
  font-weight: 500;

  .team-comparison-panel.dark-mode & {
    color: #e0e0e0;
  }
}

.rec-value {
  font-size: 26rpx;
  font-weight: 700;

  &.big-ball {
    color: #ff4757;
  }

  &.small-ball {
    color: #2ed573;
  }

  .team-comparison-panel.dark-mode & {
    color: #ffffff;

    &.big-ball {
      color: #ff6b7a;
    }

    &.small-ball {
      color: #4cd964;
    }
  }
}

.rec-reason {
  font-size: 24rpx;
  color: #333;
  flex: 1;
  line-height: 1.4;

  .team-comparison-panel.dark-mode & {
    color: #f0f0f0;
  }
}

/* 球队统计对比 */
.team-stats {
  margin-top: 30rpx;
  padding-top: 20rpx;
  border-top: 1rpx solid #f0f0f0;

  .team-comparison-panel.dark-mode & {
    border-top-color: #404040;
  }
}

.stats-title {
  font-size: 26rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 20rpx;

  .team-comparison-panel.dark-mode & {
    color: #f5f5f5;
  }
}

.stats-comparison {
  display: flex;
  align-items: flex-start;
  gap: 20rpx;
}

.team-stat {
  flex: 1;
  background-color: #f8f9fa;
  padding: 20rpx;
  border-radius: 8rpx;

  .team-comparison-panel.dark-mode & {
    background-color: #3a3a3a;
  }
}

.team-name {
  display: block;
  font-size: 26rpx;
  font-weight: 700;
  color: #333;
  margin-bottom: 15rpx;

  .team-comparison-panel.dark-mode & {
    color: #f8f8f8;
  }
}

.stat-item {
  display: block;
  font-size: 22rpx;
  color: #666;
  margin-bottom: 8rpx;

  &:last-child {
    margin-bottom: 0;
  }

  .team-comparison-panel.dark-mode & {
    color: #d0d0d0;
  }
}

.vs-divider {
  font-size: 24rpx;
  font-weight: bold;
  color: #999;
  align-self: center;
  flex-shrink: 0;

  .team-comparison-panel.dark-mode & {
    color: #666;
  }
}

/* 独立对比分析结果样式 */
.comparison-results-section {
  margin: 10rpx;
  background-color: white;
  border-radius: 8rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;

  &.dark-mode {
    background-color: #2d2d2d;
    box-shadow: 0 2rpx 8rpx rgba(255, 255, 255, 0.1);
  }
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;

  .comparison-results-section.dark-mode & {
    border-bottom-color: #404040;
  }
}

.clear-btn {
  padding: 8rpx 16rpx;
  background-color: #ff4757;
  color: white;
  border: none;
  border-radius: 4rpx;
  font-size: 22rpx;
}

.comparison-matches-list {
  padding: 10rpx;
}

.comparison-match-item {
  display: flex;
  align-items: center;
  padding: 12rpx 15rpx;
  margin-bottom: 8rpx;
  background-color: #f8f9fa;
  border-radius: 8rpx;
  border-left: 4rpx solid transparent;
  transition: all 0.3s ease;

  &.direct-match {
    border-left-color: #007aff;
    background-color: #e3f2fd;
  }

  &.mini {
    background-color: #e8f5e8;

    &.direct-match {
      background-color: #c8e6c9;
    }
  }

  &.dark-mode {
    background-color: #3a3a3a;

    &.direct-match {
      border-left-color: #0a84ff;
      background-color: #1e3a5f;
    }

    &.mini {
      background-color: #2d4a2d;

      &.direct-match {
        background-color: #1a4d1a;
      }
    }
  }
}

.highlight {
  color: #007aff !important;
  font-weight: 700 !important;

  .comparison-results-section.dark-mode & {
    color: #66b3ff !important;
  }
}

/* 球队选择弹出框样式 */
.team-selector-popup {
  background-color: white;
  border-radius: 20rpx;
  padding: 0;
  max-height: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  /* 移动端优化 */
  position: relative;
  overflow: hidden;
  /* 确保弹框本身不会滚动 */
  touch-action: pan-y;

  &.dark-mode {
    background-color: #2d2d2d;
    color: #ffffff;
  }
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  flex-shrink: 0;

  .team-selector-popup.dark-mode & {
    border-bottom-color: #404040;
  }
}

.popup-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;

  .team-selector-popup.dark-mode & {
    color: #ffffff;
  }
}

.close-btn {
  width: 50rpx;
  height: 50rpx;
  border-radius: 50%;
  background-color: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  color: #666;
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover {
    background-color: #e8e8e8;
    color: #333;
  }

  .team-selector-popup.dark-mode & {
    background-color: #4a4a4a;
    color: #ccc;

    &:hover {
      background-color: #555;
      color: #fff;
    }
  }
}

.teams-grid-container {
  flex: 1;
  height: 100%;
  /* 移动端滚动容器优化 */
  -webkit-overflow-scrolling: touch;
  /* 防止滚动穿透 */
  overscroll-behavior: contain;
  /* 确保在安卓端可以滚动 */
  scroll-behavior: smooth;
}

.teams-grid {
  padding: 30rpx;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200rpx, 1fr));
  gap: 20rpx;
  /* 移除overflow相关属性，由scroll-view处理 */
  min-height: 100%;
  /* 确保网格内容可以正常显示 */
  width: 100%;
  box-sizing: border-box;
}

.team-grid-item {
  padding: 25rpx 15rpx;
  background-color: #f8f9fa;
  border-radius: 12rpx;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 2rpx solid transparent;
  min-height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;

  &:hover {
    background-color: #e9ecef;
    transform: translateY(-2rpx);
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  }

  &.selected {
    background-color: #007aff;
    color: white;
    border-color: #0056b3;
    transform: scale(1.05);

    .team-name-text {
      color: white;
      font-weight: 600;
    }
  }

  &.dark-mode {
    background-color: #3a3a3a;
    border-color: #555;

    &:hover {
      background-color: #4a4a4a;
      box-shadow: 0 4rpx 12rpx rgba(255, 255, 255, 0.1);
    }

    &.selected {
      background-color: #0a84ff;
      border-color: #0066cc;
    }
  }
}

.team-name-text {
  font-size: 24rpx;
  color: #333;
  font-weight: 500;
  word-break: break-all;
  line-height: 1.3;

  .team-grid-item.dark-mode & {
    color: #f0f0f0;
  }
}
</style>
